package com.hzlx.config;

import com.hzlx.dao.PermissionDao;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import reactor.core.publisher.Flux;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@Slf4j
public class GatewayConfig {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Resource
    PermissionDao menuDao;
    int order = 0;
    @Bean
    public RouteDefinitionLocator dynamicRouteLocator(){
        return new RouteDefinitionLocator() {
            @Override
            public Flux<RouteDefinition> getRouteDefinitions() {
                //从数据库查询路由配置
                return Flux.fromIterable(menuDao.findAllRoutes().stream().map(perm->{
                    RouteDefinition rd = new RouteDefinition();
                    rd.setId(perm.getServiceName());
                    rd.setUri(URI.create("lb://" + perm.getServiceName()));
                    rd.setPredicates(List.of(new PredicateDefinition("Path="+perm.getUri())));
                    log.info("添加路由："+perm.getServiceName());
                    return rd;
                }).collect(Collectors.toList()));
            }
        };
    }
}
